<template>
    <el-card class="box-card">
        <header-template slot="header" ref="header"
                         :table-ref="tableOptions.ref"
                         :toolbar_buttons="headerOption.toolbar_buttons"
                         :toolbar_filter="headerOption.toolbar_filter"
                         :searchForm="searchForm"
                         @event="handleHeaderEvent">
            <template slot="right_search">
                <el-select v-model="searchForm.audit_state" class="w100" clearable
                           @change="getList(true)">
                    <el-option label="审核状态" value="" />
                    <el-option label="待审核" :value="0" />
                    <el-option label="已审核" :value="1" />
                </el-select>
            </template>
        </header-template>
        <div class="card_content">
            <vxe-table-template :data="dataList" :options.sync="tableOptions"
                                @event="handleTableEvent" />
        </div>
    </el-card>
</template>

<script>
import { mapState } from "vuex";
import provide from "@common/mixins/provide";
import poiApi from "@common/api/poiApi";
import common from "@jxc/utils/common";
import clothing from "@jxc/utils/clothing";
import ReconciliationForm from "../dialog/ReconciliationForm";
import ReconciliationExportForm from "../dialog/ReconciliationExportForm";

export default {
    extends: provide,
    name: "Reconciliation",
    props: {
        type: {
            type: String,
            default: 'sale',
        },
        container: {
            type: String,
            default: 'jxc_sale_reconciliation_container',
        },
        permission: {
            type: Object,
            default() {
                return {};
            },
        },
    },
    data() {
        const _this = this;
        return {
            supplierOptions: {
                disabled: true,
                placeholder: '供应商选择',
                bottomAction: {
                    permission: 'save_sys_supplier',
                    permissionUrl: '/sysSupplier',
                },
            },
            clientOptions: {
                disabled: false,
                placeholder: '客户选择',
                bottomAction: {
                    permission: 'save_sys_client',
                    permissionUrl: '/sysClients',
                },
            },
            searchForm: {
                audit_state: '',
                state: 1,
            },
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                    {
                        id: "add",
                        icon: "fa fa-plus",
                        type: "primary",
                        show: true,
                        permission: _this.permission.save,
                        method: () => {
                            _this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "edit",
                        icon: "fa fa-pencil",
                        type: "success",
                        show: true,
                        permission: _this.permission.save,
                        method: () => {
                            _this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "delete",
                        icon: "fa fa-trash-o",
                        type: "danger",
                        show: true,
                        permission: _this.permission.delete,
                        method: () => {
                            _this.deleteConfirm();
                        },
                    },
                    {
                        id: "audit",
                        label: '审核',
                        icon: "el-icon-top-right",
                        class: 'audit_btn',
                        show: true,
                        permission: _this.permission.audit,
                        method: () => {
                            _this.changeAuditState('audit');
                        },
                    },
                    {
                        id: "reAudit",
                        label: '反审',
                        icon: "el-icon-bottom-left",
                        class: 're_audit_btn',
                        show: true,
                        permission: _this.permission.reAudit,
                        method: () => {
                            _this.changeAuditState('reAudit');
                        },
                    },
                    {
                        id: "export",
                        label: '导出',
                        icon: "el-icon-download",
                        class: 'export_btn',
                        show: true,
                        permission: _this.permission.export,
                        method: () => {
                            _this.handleExport();
                        },
                    },
                ],
                toolbar_filter: [
                    { type: "text", field: "code", label: `对账编号` },
                    {
                        type: "selectBottom",
                        field: _this.type === 'buy' ? 'supplier_sid' : "client_sid",
                        label: _this.type === 'buy' ? '供应商' : "客户",
                        props: {
                            type: _this.type === 'buy' ? 'supplierDrawer' : "clientsDrawer",
                            options: {
                                placeholder: `选择${ _this.type === 'buy' ? '供应商' : '客户' }`,
                            },
                        },
                    },
                ],
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: `${ _this.type }JxcReconciliationTable`,
                container: `.${ _this.container }`,
                multiSelect: true,
                showSummary: true,
                summaryArray: [ "amount" ],
                columns: [],
                baseColumns: [
                    {
                        label: "审核状态",
                        prop: "audit_state",
                        align: "center",
                        minWidth: 60,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return '已审核';
                            }
                            return '待审核';
                        },
                    },
                    {
                        label: "对账周期",
                        prop: "begin_date",
                        align: "center",
                        minWidth: 90,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.begin_date) && _this.$utils.isNotEmpty(row.end_date)) {
                                return `${ row.begin_date } 至 ${ row.end_date }`;
                            }
                            return '';
                        },
                    },
                    {
                        label: "对账编号",
                        prop: "code",
                        align: "center",
                        minWidth: 90,
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "客户",
                        prop: "client_display",
                        align: "center",
                        permission: [ 'sale' ],
                    },
                    {
                        label: "供应商",
                        prop: "supplier_display",
                        align: "center",
                        permission: [ 'buy' ],
                    },
                    {
                        label: `上期末未${ _this.type === 'sale' ? '收' : '付' }款金额`,
                        prop: "pre_end_amount",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        minWidth: 100,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "本月送货发生金额",
                        prop: "amount",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        minWidth: 100,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: `本月已${ _this.type === 'sale' ? '收' : '付' }款金额`,
                        prop: "payment_amount",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        minWidth: 100,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: `至本期末未${ _this.type === 'sale' ? '收' : '付' }款金额`,
                        prop: "end_amount",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        minWidth: 120,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "部门",
                        prop: "group_name",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "录入人",
                        prop: "creator_person_name",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "录入时间",
                        prop: "create_date",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        width: 135,
                    },
                    {
                        label: "审核人",
                        prop: "auditor_person_name",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return row.auditor_person_name;
                            }
                            return '';
                        },
                    },
                    {
                        label: "审核时间",
                        prop: "audit_date",
                        align: "center",
                        width: 135,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return row.audit_date;
                            }
                            return '';
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    count: 2,
                    list: [
                        {
                            id: "info",
                            icon: "fa fa-info-circle",
                            type: "warning ",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "详情",
                            },
                            filter(row) {
                                return row.state === 0 || (row.state === 1 && row.audit_state === 1);
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'detail');
                            },
                        },
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            type: "success",
                            size: "mini",
                            show: true,
                            permission: _this.permission.save,
                            tooltip: {
                                content: "编辑",
                            },
                            filter(row) {
                                return row.state === 1 && row.audit_state === 0;
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'edit');
                            },
                        },
                        {
                            id: "delete",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            permission: _this.permission.delete,
                            tooltip: {
                                content: "删除",
                            },
                            filter(row) {
                                return row.state === 1 && row.audit_state === 0;
                            },
                            method: (index, row) => {
                                _this.deleteConfirm(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
        };
    },
    computed: {
        ...mapState(['user_setting']),
        ...mapState('jxc', ['setting']),
    },
    mounted() {
        this.init();
    },
    methods: {
        async init() {
            const _this = this;
            await _this.storeDispatch('jxc/initSetting');
            this.initOptions();
            this.getList(true);
        },
        initOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = columns.filter(item => item.permission.indexOf(_this.type) !== -1);
            _this.tableOptions = $.extend({}, _this.tableOptions, { columns });
        },
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === 'search') {
                _this.getList(true)
            } else if (event.type === 'refresh') {
                _this.getList(true)
            }
        },
        getList(query) {
            const _this = this;
            _this.selectionList = [];
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            queryData.type = _this.type;
            _this.fetchData(_this.$api.API_FindJxcFinancePaymentRequests, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        openDialog(row, type) {
            const _this = this;
            if (type === 'edit' && row == null) {
                if (!_this.checkSelection(_this.selectionList, false)) {
                    return;
                }
                row = _this.selectionList[0];
            }
            if (!row) {
                row = {};
            }
            let detail = type === 'detail';
            _this.$dialog({
                title: _this.type === 'sale' ? '销售对账单' : '采购对账单',
                width: '1200px',
                component: {
                    value: ReconciliationForm,
                    props: {
                        detail,
                        row,
                        type: _this.type,
                    },
                },
                hideConfirmBtn: detail,
                confirmed() {
                    _this.getList();
                },
            });
        },
        async changeAuditState(type) {
            const _this = this;
            let label = _this.type === 'sale' ? '销售对账单' : '采购对账单';
            let list = await common.checkRow(_this, {
                type,
                selectionList: _this.selectionList,
                label,
                auditCheck: type === 'audit' ? 1 : 0,
            });
            if (!list) {
                return;
            }
            _this.fetchData(_this.$api.API_ChangeJxcFinancePaymentRequestAuditState, {
                sid_list: list.map(item => item.sid),
                state: type === 'audit' ? 1 : -1,
            }).then(() => {
                _this.$message.success(`${ type === 'audit' ? '审核' : '反审' }成功！`);
                _this.getList();
            }).catch(() => {
            });
        },
        async deleteConfirm(row) {
            const _this = this;
            let label = _this.type === 'sale' ? '销售对账单' : '采购对账单';
            let list = await common.checkRow(_this, {
                type: 'delete', row,
                selectionList: _this.selectionList,
                label,
            });
            if (!list) {
                return;
            }
            _this.fetchData(_this.$api.API_DeleteJxcFinancePaymentRequests, {
                sid_list: list.map(item => item.sid),
            }).then(() => {
                _this.$message.success('删除成功！');
                _this.getList();
            }).catch(() => {
            });
        },
        handleExport() {
            const _this = this;
            let check = _this.checkSelection(_this.selectionList);
            if (!check) {
                return;
            }
            let label = _this.type === 'sale' ? '销售对账单' : '采购对账单';
            let template_name = _this.$api.EXPORT_TEMPLATE_NAME_JXC_FIN_PAYMENT_REQUEST;
            if (clothing.isClothing(_this.setting)) {
                template_name = _this.$api.EXPORT_TEMPLATE_NAME_JXC_CLOTHING_FIN_PAYMENT_REQUEST;
            }
            _this.$ExportForm({
                method: 'exportExcelTemplateCustomNew',
                params: {
                    template_name,
                    url: _this.$api.API_GetRequestExportData,
                    params: {
                        sid: _this.selectionList[0].sid,
                    },
                    output_name: `${_this.type === 'sale'?_this.selectionList[0].client_display:_this.selectionList[0].supplier_display }-${ label }`,
                    col_foreach: true,
                },
                dialogOpt: {
                    title: `导出${ label }`,
                    formConfig: {
                        rules: {
                            company_name: [
                                { required: true, message: "请输入公司名称", trigger: "change" },
                            ],
                            bank_account: [
                                { required: true, message: "请输入银行账号", trigger: "change" },
                            ],
                            bank: [
                                { required: true, message: "请输入开户行", trigger: "change" },
                            ],
                            linker_name: [
                                { required: true, message: "请输入联系人", trigger: "change" },
                            ],
                            linker_phone: [
                                { required: true, message: "请输入联系电话", trigger: "change" },
                            ],
                            linker_address: [
                                { required: true, message: "请输入通讯地址", trigger: "change" },
                            ],
                            the_date: [
                                { required: true, message: "请选择日期", trigger: "change" },
                            ],
                        },
                        labelWidth: '80px',
                        itemField: {
                            tip: null,
                            company_name: '公司名称',
                            bank_account: '银行账号',
                            bank: '开户行',
                            linker_name: '联系人',
                            linker_phone: '联系电话',
                            linker_address: '通讯地址',
                            the_date: '日期',
                        },
                        itemWidget: {
                            the_date: {
                                name: 'ElDatePicker',
                                style: {
                                    width: '100%',
                                },
                            },
                        },
                        itemProps: {
                            tip: {
                                labelWidth: '0px',
                                style: {
                                    marginBottom: '5px',
                                },
                                widget: {
                                    name: 'ElAlert',
                                    style: {
                                        padding: '2px',
                                    },
                                    props: {
                                        title: '单据项预设值',
                                        closable: false,
                                        effect: 'dark',
                                    },
                                },
                            },
                        },
                    },
                },
            });
        },
    },
}
</script>

<style scoped>

</style>
